package handler

import (
	"0507zk/api/client"
	"0507zk/api/models"
	product "0507zk/common/proto"
	"0507zk/pkg"
	"github.com/gin-gonic/gin"
	"net/http"
)

func UserSendSms(c *gin.Context) {
	var data models.SendSms
	if err := c.ShouldBind(&data); err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 0,
			"msg":  err.Error(),
			"data": nil,
		})
		return
	}

	sms, err := client.SendSms(c, &product.SendSmsReq{
		Mobile: data.Mobile,
		Router: data.Router,
	})
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 0,
			"msg":  err.Error(),
			"data": nil,
		})
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "短信验证码发送成功",
		"data": sms,
	})
}

func UserLogin(c *gin.Context) {
	var data models.Login
	if err := c.ShouldBind(&data); err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 0,
			"msg":  err.Error(),
			"data": nil,
		})
		return
	}
	login, err := client.UserLogin(c, &product.UserLoginReq{
		Mobile:   data.Mobile,
		Password: data.Password,
		Code:     data.Code,
	})
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 0,
			"msg":  err.Error(),
			"data": nil,
		})
		return
	}
	claims := pkg.CustomClaims{
		ID: uint(login.UserId),
	}
	token, err := pkg.NewJWT("2209A").CreateToken(claims)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 0,
			"msg":  "token生成错误",
			"data": nil,
		})
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "用户登录成功",
		"data": token,
	})
}

func ProductList(c *gin.Context) {
	var data models.List
	if err := c.ShouldBind(&data); err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 0,
			"msg":  err.Error(),
			"data": nil,
		})
		return
	}

	sms, err := client.UserList(c, &product.ProductListReq{
		Name: data.Name,
	})
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 0,
			"msg":  err.Error(),
			"data": nil,
		})
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "商品列表展示成功",
		"data": sms,
	})
	return
}
